package com.hwadee.backend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hwadee.backend.dao.UserDao;
import com.hwadee.backend.entity.user.RegisterRequest;
import com.hwadee.backend.entity.user.UpdateUserRequest;
import com.hwadee.backend.entity.user.User;
import com.hwadee.backend.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDao userDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public Result register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userDao.selectOne(new QueryWrapper<User>().eq("username", request.getUsername())) != null) {
            return Result.error("用户名已存在");
        }

        User user = new User();
        user.setUsername(request.getUsername());
        // 密码加密
        user.setPassword(passwordEncoder.encode(request.getPassword())); 
        user.setAge(request.getAge());
        user.setSex(request.getSex());
        user.setPhone(request.getPhone());
        user.setRole(request.getRole());
        // 设置状态，默认为active
        user.setStatus(request.getStatus() != null ? request.getStatus() : "active");

        // 验证状态值是否合法
        if (!"active".equals(user.getStatus()) && !"inactive".equals(user.getStatus())) {
            return Result.error("无效的状态值，必须是active或inactive");
        }

        userDao.insert(user);
        return Result.success("注册成功");
    }

    public Result login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userDao.selectOne(queryWrapper);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            // 清除密码字段，避免返回给前端
            user.setPassword(null);
            return Result.success(user);
        }
        return Result.error("用户名或密码错误");
    }

    public Result getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userDao.selectOne(queryWrapper);
        if (user != null) {
            user.setPassword(null); // 清除密码
            return Result.success(user);
        }
        return Result.error("用户不存在");
    }

    public Result updateUser(UpdateUserRequest request) {
        logger.info("开始更新用户信息: ID={}, 用户名={}", request.getId(), request.getUsername());

        // 1. 验证用户是否存在
        User existingUser = userDao.selectById(request.getId());
        if (existingUser == null) {
            logger.warn("更新失败: 用户ID={}不存在", request.getId());
            return Result.error("用户不存在");
        }

        // 2. 如果修改了用户名，检查新用户名是否已被占用
        if (!existingUser.getUsername().equals(request.getUsername())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", request.getUsername());
            User userWithSameUsername = userDao.selectOne(queryWrapper);
            if (userWithSameUsername != null) {
                logger.warn("更新失败: 用户名{}已存在", request.getUsername());
                return Result.error("用户名已存在");
            }
        }

        // 3. 构建更新对象
        User user = new User();
        user.setId(request.getId());
        user.setUsername(request.getUsername());
        user.setSex(request.getSex());
        user.setAge(request.getAge());
        user.setPhone(request.getPhone());
        // 添加用户状态更新
        if (request.getStatus() != null && !request.getStatus().isEmpty()) {
            // 验证状态值是否合法
            if (!"active".equals(request.getStatus()) && !"banned".equals(request.getStatus())) {
                logger.warn("用户ID={}状态更新失败：无效状态值{}", request.getId(), request.getStatus());
                return Result.error("用户状态只能是'active'或'banned'");
            }
            user.setStatus(request.getStatus());
            logger.info("用户ID={}状态更新为{}", request.getId(), request.getStatus());
        }

        // 4. 如果提供了新密码，则更新密码
        if (request.getPassword() != null && !request.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            logger.info("用户ID={}请求更新密码", request.getId());
        }

        // 5. 执行更新操作
        int rows = userDao.updateById(user);

        if (rows > 0) {
            logger.info("用户ID={}信息更新成功", request.getId());
            return Result.success("用户信息更新成功");
        } else {
            logger.error("用户ID={}信息更新失败", request.getId());
            return Result.error("用户信息更新失败");
        }
    }

    public Result updateUsername(int id, String username) {
        try {
            // 1. 验证用户是否存在
            User existingUser = userDao.selectById(id);
            if (existingUser == null) {
                logger.warn("更新用户名失败: 用户ID={}不存在", id);
                return Result.error("用户不存在");
            }

            // 2. 检查新用户名是否已被占用
            if (!existingUser.getUsername().equals(username)) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("username", username);
                User userWithSameUsername = userDao.selectOne(queryWrapper);
                if (userWithSameUsername != null) {
                    logger.warn("更新用户名失败: 用户名{}已存在", username);
                    return Result.error("用户名已存在");
                }
            }

            // 3. 仅更新用户名，保留其他字段原值
            existingUser.setUsername(username);

            // 4. 执行更新操作
            int rows = userDao.updateById(existingUser);

            if (rows > 0) {
                logger.info("用户ID={}用户名更新成功: {}", id, username);
                return Result.success("用户名更新成功");
            } else {
                logger.error("用户ID={}用户名更新失败", id);
                return Result.error("用户名更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户名发生异常: {}", e.getMessage(), e);
            return Result.error("更新用户名失败: " + e.getMessage());
        }
    }

    public Result getAllUsers() {
        try {
            List<User> users = userDao.selectList(null);
            if (users == null) {
                users = new ArrayList<>();
            }
            // 转换状态为中文显示
            for (User user : users) {
                if ("active".equals(user.getStatus())) {
                    user.setStatus("正常");
                } else if ("inactive".equals(user.getStatus())) {
                    user.setStatus("封号斗罗");
                }
                user.setPassword(null);
            }
            return Result.success(users);
        } catch (Exception e) {
            return Result.error("查询用户列表失败: " + e.getMessage());
        }
    }

    public Result resetPassword(int id, String password) {
        try {
            User user = userDao.selectById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            user.setPassword(passwordEncoder.encode(password));
            userDao.updateById(user);
            return Result.success("密码重置成功");
        } catch (Exception e) {
            return Result.error("重置密码失败: " + e.getMessage());
        }
    }

    public Result updateStatus(int id, String status) {
        try {
            User user = userDao.selectById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            if (!"active".equals(status) && !"inactive".equals(status)) {
                return Result.error("无效的状态值");
            }
            user.setStatus(status);
            userDao.updateById(user);
            return Result.success("状态更新成功");
        } catch (Exception e) {
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }

    public Result deleteUser(int id) {
        try {
            User user = userDao.selectById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            userDao.deleteById(id);
            return Result.success("用户删除成功");
        } catch (Exception e) {
            return Result.error("删除用户失败: " + e.getMessage());
        }
    }

    public Result getUserPassword(int id) {
        try {
            logger.info("查询用户ID: {} 的密码", id);
            String password = userDao.selectPasswordById(id);
            logger.info("密码是："+password);
            logger.info("查询结果: 密码 {}", password != null ? "已获取" : "为空");
            if (password == null || password.trim().isEmpty()) {
                return Result.error("用户密码未设置或为空");
            }
            return Result.success(password);
        } catch (Exception e) {
            logger.error("获取密码失败", e);
            return Result.error("获取密码失败: " + e.getMessage());
        }
    }

    public List<User> getUsersByRole(String role) {
        logger.info("查询角色为:{}的用户列表", role);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", role);
        List<User> users = userDao.selectList(queryWrapper);
        logger.info("查询结果数量: {}", users.size());
        return users;
    }

    public User getUserById(Long id) {
        return userDao.selectById(id);
    }
}